{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "48cd92ca",
   "metadata": {},
   "source": [
    "# week10 语音识别"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7943dfd7",
   "metadata": {},
   "source": [
    "# 本周内容\n",
    "## 知识概念\n",
    ">1. 一切都是I/O：软工到产品的一般化知识\n",
    ">2. 语音识别:speech recognition\n",
    ">3. 语音唤醒\n",
    ">4. 自动语音识别:Automatic Speech Recognition, 简称 ASR\n",
    ">>1. 其目标是以电脑自动将人类的语音内容转换为相应的文字。与说话人识别及说话人确认不同，后者尝试识别或确认发出语音的说话人而非其中所包含的词汇内容。\n",
    ">>2. 语音合成:text to speech,简称 TTS\n",
    ">>3. 将文字转化为语音的一种技术，类似于人类的嘴巴，通过不同的音色说出想表达的内容。 在语音合成技术中，主要分为 语言分析部分 和 声学系统部分 ，也称为 前端部分 和 后端部分， 语言分析部分主要是根据输入的文字信息进行分析，生成对应的语言学规格书，想好该怎么读；声学系统部分主要是根据语音分析部分提供的语音学规格书，生成对应的音频，实现发声的功能。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "77a1695d",
   "metadata": {},
   "source": [
    "## 语音识别测试-百度API-ASR"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "1b345987",
   "metadata": {},
   "outputs": [],
   "source": [
    "API_KEY = 'smxkOHWjqLVljEmIry5vuSYI'\n",
    "SECRET_KEY = 'ky3FZeSSDurxLyLLqZ2kPaEnts9NH1W1'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "51c6e245",
   "metadata": {},
   "outputs": [],
   "source": [
    "# coding=utf-8\n",
    "\n",
    "import sys\n",
    "import json\n",
    "import time\n",
    "\n",
    "IS_PY3 = sys.version_info.major == 3\n",
    "\n",
    "if IS_PY3:\n",
    "    from urllib.request import urlopen\n",
    "    from urllib.request import Request\n",
    "    from urllib.error import URLError\n",
    "    from urllib.parse import urlencode\n",
    "\n",
    "    timer = time.perf_counter\n",
    "else:\n",
    "    import urllib2\n",
    "    from urllib2 import urlopen\n",
    "    from urllib2 import Request\n",
    "    from urllib2 import URLError\n",
    "    from urllib import urlencode\n",
    "\n",
    "    if sys.platform == \"win32\":\n",
    "        timer = time.clock\n",
    "    else:\n",
    "        # On most other platforms the best timer is time.time()\n",
    "        timer = time.time\n",
    "        \n",
    "# 需要识别的文件\n",
    "AUDIO_FILE = 'audio/16k.wav'  # 只支持 pcm/wav/amr 格式，极速版额外支持m4a 格式\n",
    "# 文件格式\n",
    "FORMAT = AUDIO_FILE[-3:];  # 文件后缀只支持 pcm/wav/amr 格式，极速版额外支持m4a 格式\n",
    "\n",
    "CUID = '123456PYTHON';\n",
    "# 采样率\n",
    "RATE = 16000;  # 固定值\n",
    "\n",
    "# 普通版\n",
    "\n",
    "DEV_PID = 1537;  # 1537 表示识别普通话，使用输入法模型。根据文档填写PID，选择语言及识别模型\n",
    "ASR_URL = 'http://vop.baidu.com/server_api'\n",
    "SCOPE = 'audio_voice_assistant_get'  # 有此scope表示有asr能力，没有请在网页里勾选，非常旧的应用可能没有\n",
    "\n",
    "# 极速版\n",
    "\n",
    "class DemoError(Exception):\n",
    "    pass\n",
    "\n",
    "\n",
    "\"\"\"  TOKEN start \"\"\"\n",
    "\n",
    "TOKEN_URL = 'http://aip.baidubce.com/oauth/2.0/token'\n",
    "\n",
    "\n",
    "def fetch_token(API_KEY,SECRET_KEY):\n",
    "    params = {'grant_type': 'client_credentials',\n",
    "              'client_id': API_KEY,\n",
    "              'client_secret': SECRET_KEY}\n",
    "    post_data = urlencode(params)\n",
    "    if (IS_PY3):\n",
    "        post_data = post_data.encode('utf-8')\n",
    "    req = Request(TOKEN_URL, post_data)\n",
    "    try:\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "    except URLError as err:\n",
    "        print('token http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "    if (IS_PY3):\n",
    "        result_str = result_str.decode()\n",
    "        \n",
    "#     print(result_str)\n",
    "    result = json.loads(result_str)\n",
    "#     print(result)\n",
    "    if ('access_token' in result.keys() and 'scope' in result.keys()):\n",
    "        if SCOPE and (not SCOPE in result['scope'].split(' ')):  # SCOPE = False 忽略检查\n",
    "            raise DemoError('scope is not correct')\n",
    "#         print('SUCCESS WITH TOKEN: %s ; EXPIRES IN SECONDS: %s' % (result['access_token'], result['expires_in']))\n",
    "        return result['access_token']\n",
    "    else:\n",
    "        raise DemoError('MAYBE API_KEY or SECRET_KEY not correct: access_token or scope not found in token response')\n",
    "\n",
    "\"\"\"  TOKEN end \"\"\"\n",
    "\n",
    "def asr(token,AUDIO_FILE):\n",
    "    speech_data = []\n",
    "    with open(AUDIO_FILE, 'rb') as speech_file:\n",
    "        speech_data = speech_file.read()\n",
    "    length = len(speech_data)\n",
    "    if length == 0:\n",
    "        raise DemoError('file %s length read 0 bytes' % AUDIO_FILE)\n",
    "\n",
    "    params = {'cuid': CUID, 'token': token, 'dev_pid': DEV_PID}\n",
    "    #测试自训练平台需要打开以下信息\n",
    "    #params = {'cuid': CUID, 'token': token, 'dev_pid': DEV_PID, 'lm_id' : LM_ID}\n",
    "    params_query = urlencode(params);\n",
    "\n",
    "    headers = {\n",
    "        'Content-Type': 'audio/' + FORMAT + '; rate=' + str(RATE),\n",
    "        'Content-Length': length\n",
    "    }\n",
    "\n",
    "    url = ASR_URL + \"?\" + params_query\n",
    "#     print(\"url is\", url);\n",
    "#     print(\"header is\", headers)\n",
    "    # print post_data\n",
    "    req = Request(ASR_URL + \"?\" + params_query, speech_data, headers)\n",
    "    try:\n",
    "        begin = timer()\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "        print(\"Request time cost %f\" % (timer() - begin))\n",
    "    except  URLError as err:\n",
    "        print('asr http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "\n",
    "    if (IS_PY3):\n",
    "        result_str = str(result_str, 'utf-8')\n",
    "#     print(result_str)\n",
    "    with open(\"result.txt\", \"w\") as of:\n",
    "        of.write(result_str)\n",
    "    return result_str"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "f5781d59",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 语音识别执行如下："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "38a3fa2f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'24.8553a7a1c737c50ca9aeae0b35da95ba.2592000.1690708837.282335-19331335'"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "xu_token = fetch_token(API_KEY,SECRET_KEY)\n",
    "xu_token"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "e47d4fc9",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "ename": "FileNotFoundError",
     "evalue": "[Errno 2] No such file or directory: 'audio/16k.wav'",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mFileNotFoundError\u001b[0m                         Traceback (most recent call last)",
      "Input \u001b[0;32mIn [9]\u001b[0m, in \u001b[0;36m<cell line: 1>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0m \u001b[43masr\u001b[49m\u001b[43m(\u001b[49m\u001b[43mxu_token\u001b[49m\u001b[43m,\u001b[49m\u001b[38;5;124;43m'\u001b[39;49m\u001b[38;5;124;43maudio/16k.wav\u001b[39;49m\u001b[38;5;124;43m'\u001b[39;49m\u001b[43m)\u001b[49m\n",
      "Input \u001b[0;32mIn [6]\u001b[0m, in \u001b[0;36masr\u001b[0;34m(token, AUDIO_FILE)\u001b[0m\n\u001b[1;32m     85\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21masr\u001b[39m(token,AUDIO_FILE):\n\u001b[1;32m     86\u001b[0m     speech_data \u001b[38;5;241m=\u001b[39m []\n\u001b[0;32m---> 87\u001b[0m     \u001b[38;5;28;01mwith\u001b[39;00m \u001b[38;5;28;43mopen\u001b[39;49m\u001b[43m(\u001b[49m\u001b[43mAUDIO_FILE\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;124;43m'\u001b[39;49m\u001b[38;5;124;43mrb\u001b[39;49m\u001b[38;5;124;43m'\u001b[39;49m\u001b[43m)\u001b[49m \u001b[38;5;28;01mas\u001b[39;00m speech_file:\n\u001b[1;32m     88\u001b[0m         speech_data \u001b[38;5;241m=\u001b[39m speech_file\u001b[38;5;241m.\u001b[39mread()\n\u001b[1;32m     89\u001b[0m     length \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mlen\u001b[39m(speech_data)\n",
      "\u001b[0;31mFileNotFoundError\u001b[0m: [Errno 2] No such file or directory: 'audio/16k.wav'"
     ]
    }
   ],
   "source": [
    "asr(xu_token,'audio/16k.wav')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d459c465",
   "metadata": {},
   "source": [
    "## 语音识别自动回复文本机器人\n",
    ">1. 准备录制音频文件\n",
    ">2. 调用语音识别，将音频转成文本\n",
    ">3. 文本自动回复.  原理: 问和答，I/O 输入和输出----特点： key:value"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6f506688",
   "metadata": {},
   "source": [
    "准备录制音频文件"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "427ca518",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Requirement already satisfied: SpeechRecognition in /Users/henjunhao/opt/anaconda3/lib/python3.9/site-packages (3.10.0)\r\n",
      "Requirement already satisfied: requests>=2.26.0 in /Users/henjunhao/opt/anaconda3/lib/python3.9/site-packages (from SpeechRecognition) (2.27.1)\r\n",
      "Requirement already satisfied: certifi>=2017.4.17 in /Users/henjunhao/opt/anaconda3/lib/python3.9/site-packages (from requests>=2.26.0->SpeechRecognition) (2022.5.18.1)\r\n",
      "Requirement already satisfied: idna<4,>=2.5 in /Users/henjunhao/opt/anaconda3/lib/python3.9/site-packages (from requests>=2.26.0->SpeechRecognition) (3.3)\r\n",
      "Requirement already satisfied: urllib3<1.27,>=1.21.1 in /Users/henjunhao/opt/anaconda3/lib/python3.9/site-packages (from requests>=2.26.0->SpeechRecognition) (1.26.9)\r\n",
      "Requirement already satisfied: charset-normalizer~=2.0.0 in /Users/henjunhao/opt/anaconda3/lib/python3.9/site-packages (from requests>=2.26.0->SpeechRecognition) (2.0.4)\r\n"
     ]
    }
   ],
   "source": [
    "!pip install SpeechRecognition"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "7b68d711",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Collecting PyAudio\n",
      "  Using cached PyAudio-0.2.13.tar.gz (46 kB)\n",
      "  Installing build dependencies ... \u001b[?25ldone\n",
      "\u001b[?25h  Getting requirements to build wheel ... \u001b[?25ldone\n",
      "\u001b[?25h    Preparing wheel metadata ... \u001b[?25ldone\n",
      "\u001b[?25hBuilding wheels for collected packages: PyAudio\n",
      "  Building wheel for PyAudio (PEP 517) ... \u001b[?25lerror\n",
      "\u001b[31m  ERROR: Command errored out with exit status 1:\n",
      "   command: /Users/henjunhao/opt/anaconda3/bin/python /Users/henjunhao/opt/anaconda3/lib/python3.9/site-packages/pip/_vendor/pep517/in_process/_in_process.py build_wheel /var/folders/lh/hqwgk6ls20bc34wz5td3kn1m0000gn/T/tmptr7r1r2p\n",
      "       cwd: /private/var/folders/lh/hqwgk6ls20bc34wz5td3kn1m0000gn/T/pip-install-fclbanmt/pyaudio_9f39d78ca8304cf28e9b4c187acbde38\n",
      "  Complete output (15 lines):\n",
      "  running bdist_wheel\n",
      "  running build\n",
      "  running build_py\n",
      "  creating build\n",
      "  creating build/lib.macosx-11.1-arm64-cpython-39\n",
      "  creating build/lib.macosx-11.1-arm64-cpython-39/pyaudio\n",
      "  copying src/pyaudio/__init__.py -> build/lib.macosx-11.1-arm64-cpython-39/pyaudio\n",
      "  running build_ext\n",
      "  building 'pyaudio._portaudio' extension\n",
      "  creating build/temp.macosx-11.1-arm64-cpython-39\n",
      "  creating build/temp.macosx-11.1-arm64-cpython-39/src\n",
      "  creating build/temp.macosx-11.1-arm64-cpython-39/src/pyaudio\n",
      "  clang -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -fwrapv -O2 -Wall -fPIC -O2 -isystem /Users/henjunhao/opt/anaconda3/include -arch arm64 -I/Users/henjunhao/opt/anaconda3/include -fPIC -O2 -isystem /Users/henjunhao/opt/anaconda3/include -arch arm64 -DMACOS=1 -I/usr/local/include -I/usr/include -I/opt/homebrew/include -I/Users/henjunhao/opt/anaconda3/include/python3.9 -c src/pyaudio/device_api.c -o build/temp.macosx-11.1-arm64-cpython-39/src/pyaudio/device_api.o\n",
      "  xcode-select: note: no developer tools were found at '/Applications/Xcode.app', requesting install. Choose an option in the dialog to download the command line developer tools.\n",
      "  error: command '/usr/bin/clang' failed with exit code 1\n",
      "  ----------------------------------------\u001b[0m\n",
      "\u001b[31m  ERROR: Failed building wheel for PyAudio\u001b[0m\n",
      "\u001b[?25hFailed to build PyAudio\n",
      "\u001b[31mERROR: Could not build wheels for PyAudio which use PEP 517 and cannot be installed directly\u001b[0m\n",
      "Requirement already satisfied: pipwin in /Users/henjunhao/opt/anaconda3/lib/python3.9/site-packages (0.5.2)\n",
      "Requirement already satisfied: docopt in /Users/henjunhao/opt/anaconda3/lib/python3.9/site-packages (from pipwin) (0.6.2)\n",
      "Requirement already satisfied: packaging in /Users/henjunhao/opt/anaconda3/lib/python3.9/site-packages (from pipwin) (21.3)\n",
      "Requirement already satisfied: requests in /Users/henjunhao/opt/anaconda3/lib/python3.9/site-packages (from pipwin) (2.27.1)\n",
      "Requirement already satisfied: six in /Users/henjunhao/opt/anaconda3/lib/python3.9/site-packages (from pipwin) (1.16.0)\n",
      "Requirement already satisfied: beautifulsoup4>=4.9.0 in /Users/henjunhao/opt/anaconda3/lib/python3.9/site-packages (from pipwin) (4.11.1)\n",
      "Requirement already satisfied: js2py in /Users/henjunhao/opt/anaconda3/lib/python3.9/site-packages (from pipwin) (0.74)\n",
      "Requirement already satisfied: pySmartDL>=1.3.1 in /Users/henjunhao/opt/anaconda3/lib/python3.9/site-packages (from pipwin) (1.3.4)\n",
      "Requirement already satisfied: pyprind in /Users/henjunhao/opt/anaconda3/lib/python3.9/site-packages (from pipwin) (2.11.3)\n",
      "Requirement already satisfied: soupsieve>1.2 in /Users/henjunhao/opt/anaconda3/lib/python3.9/site-packages (from beautifulsoup4>=4.9.0->pipwin) (2.3.1)\n",
      "Requirement already satisfied: tzlocal>=1.2 in /Users/henjunhao/opt/anaconda3/lib/python3.9/site-packages (from js2py->pipwin) (5.0.1)\n",
      "Requirement already satisfied: pyjsparser>=2.5.1 in /Users/henjunhao/opt/anaconda3/lib/python3.9/site-packages (from js2py->pipwin) (2.7.1)\n",
      "Requirement already satisfied: pyparsing!=3.0.5,>=2.0.2 in /Users/henjunhao/opt/anaconda3/lib/python3.9/site-packages (from packaging->pipwin) (3.0.4)\n",
      "Requirement already satisfied: idna<4,>=2.5 in /Users/henjunhao/opt/anaconda3/lib/python3.9/site-packages (from requests->pipwin) (3.3)\n",
      "Requirement already satisfied: certifi>=2017.4.17 in /Users/henjunhao/opt/anaconda3/lib/python3.9/site-packages (from requests->pipwin) (2022.5.18.1)\n",
      "Requirement already satisfied: urllib3<1.27,>=1.21.1 in /Users/henjunhao/opt/anaconda3/lib/python3.9/site-packages (from requests->pipwin) (1.26.9)\n",
      "Requirement already satisfied: charset-normalizer~=2.0.0 in /Users/henjunhao/opt/anaconda3/lib/python3.9/site-packages (from requests->pipwin) (2.0.4)\n",
      "Usage:\n",
      "  pipwin install (<package> | [-r=<file> | --file=<file>]) [--proxy=<proxy>]\n",
      "  pipwin uninstall <package>\n",
      "  pipwin download (<package> | [-r=<file> | --file=<file>]) [-d=<dest> | --dest=<dest>] [--proxy=<proxy>]\n",
      "  pipwin search <package> [--proxy=<proxy>]\n",
      "  pipwin list\n",
      "  pipwin refresh [--log=<log>] [--proxy=<proxy>]\n",
      "  pipwin (-h | --help)\n",
      "  pipwin (-v | --version)\n"
     ]
    }
   ],
   "source": [
    "!pip install PyAudio\n",
    "\n",
    "!pip install pipwin\n",
    "!pipwin instll PyAudio"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "3e5b85e1",
   "metadata": {},
   "outputs": [
    {
     "ename": "AttributeError",
     "evalue": "Could not find PyAudio; check installation",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mModuleNotFoundError\u001b[0m                       Traceback (most recent call last)",
      "File \u001b[0;32m~/opt/anaconda3/lib/python3.9/site-packages/speech_recognition/__init__.py:108\u001b[0m, in \u001b[0;36mMicrophone.get_pyaudio\u001b[0;34m()\u001b[0m\n\u001b[1;32m    107\u001b[0m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[0;32m--> 108\u001b[0m     \u001b[38;5;28;01mimport\u001b[39;00m \u001b[38;5;21;01mpyaudio\u001b[39;00m\n\u001b[1;32m    109\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mImportError\u001b[39;00m:\n",
      "\u001b[0;31mModuleNotFoundError\u001b[0m: No module named 'pyaudio'",
      "\nDuring handling of the above exception, another exception occurred:\n",
      "\u001b[0;31mAttributeError\u001b[0m                            Traceback (most recent call last)",
      "Input \u001b[0;32mIn [13]\u001b[0m, in \u001b[0;36m<cell line: 3>\u001b[0;34m()\u001b[0m\n\u001b[1;32m      1\u001b[0m \u001b[38;5;28;01mimport\u001b[39;00m \u001b[38;5;21;01mspeech_recognition\u001b[39;00m\n\u001b[1;32m      2\u001b[0m r \u001b[38;5;241m=\u001b[39m speech_recognition\u001b[38;5;241m.\u001b[39mRecognizer()\n\u001b[0;32m----> 3\u001b[0m \u001b[38;5;28;01mwith\u001b[39;00m \u001b[43mspeech_recognition\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mMicrophone\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m \u001b[38;5;28;01mas\u001b[39;00m source:\n\u001b[1;32m      4\u001b[0m     audio \u001b[38;5;241m=\u001b[39m r\u001b[38;5;241m.\u001b[39mlisten(source)\n\u001b[1;32m      5\u001b[0m \u001b[38;5;66;03m# 将数据保存到wav文件中\u001b[39;00m\n",
      "File \u001b[0;32m~/opt/anaconda3/lib/python3.9/site-packages/speech_recognition/__init__.py:80\u001b[0m, in \u001b[0;36mMicrophone.__init__\u001b[0;34m(self, device_index, sample_rate, chunk_size)\u001b[0m\n\u001b[1;32m     77\u001b[0m \u001b[38;5;28;01massert\u001b[39;00m \u001b[38;5;28misinstance\u001b[39m(chunk_size, \u001b[38;5;28mint\u001b[39m) \u001b[38;5;129;01mand\u001b[39;00m chunk_size \u001b[38;5;241m>\u001b[39m \u001b[38;5;241m0\u001b[39m, \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mChunk size must be a positive integer\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m     79\u001b[0m \u001b[38;5;66;03m# set up PyAudio\u001b[39;00m\n\u001b[0;32m---> 80\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mpyaudio_module \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mget_pyaudio\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m     81\u001b[0m audio \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mpyaudio_module\u001b[38;5;241m.\u001b[39mPyAudio()\n\u001b[1;32m     82\u001b[0m \u001b[38;5;28;01mtry\u001b[39;00m:\n",
      "File \u001b[0;32m~/opt/anaconda3/lib/python3.9/site-packages/speech_recognition/__init__.py:110\u001b[0m, in \u001b[0;36mMicrophone.get_pyaudio\u001b[0;34m()\u001b[0m\n\u001b[1;32m    108\u001b[0m     \u001b[38;5;28;01mimport\u001b[39;00m \u001b[38;5;21;01mpyaudio\u001b[39;00m\n\u001b[1;32m    109\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mImportError\u001b[39;00m:\n\u001b[0;32m--> 110\u001b[0m     \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mAttributeError\u001b[39;00m(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mCould not find PyAudio; check installation\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[1;32m    111\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01mdistutils\u001b[39;00m\u001b[38;5;21;01m.\u001b[39;00m\u001b[38;5;21;01mversion\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m LooseVersion\n\u001b[1;32m    112\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m LooseVersion(pyaudio\u001b[38;5;241m.\u001b[39m__version__) \u001b[38;5;241m<\u001b[39m LooseVersion(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m0.2.11\u001b[39m\u001b[38;5;124m\"\u001b[39m):\n",
      "\u001b[0;31mAttributeError\u001b[0m: Could not find PyAudio; check installation"
     ]
    }
   ],
   "source": [
    "import speech_recognition\n",
    "r = speech_recognition.Recognizer()\n",
    "with speech_recognition.Microphone() as source:\n",
    "    audio = r.listen(source)\n",
    "# 将数据保存到wav文件中\n",
    "with open(\"1.wav\", \"wb\") as f: \n",
    "    f.write(audio.get_wav_data(convert_rate=16000))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ffddd039",
   "metadata": {},
   "source": [
    "文本自动回复（自定义）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4eaeaede",
   "metadata": {},
   "outputs": [],
   "source": [
    "qa = {\n",
    "    \"你好\":\"你好呀，有什么事么？\",\n",
    "    \"你叫什么名字\":\"我是人见人爱，花见花开的小小度呀\",\n",
    "    \"你多大了\":\"这是很私密的问题，我今年18岁了。\",\n",
    "    \"苹果用英文怎么说\":\"apple\",\n",
    "    \"今天天气\":\"我这边墨迹天气显示，今天广州30度，晴\"\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "807e96fe",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
